package com.umakr.ax.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
/**
 *
 * @author sc
 * @date 2018/1/24
 */
public class FormatPhotoUrlUtil {
    protected static final Log logger = LogFactory.getLog(FormatPhotoUrlUtil.class);
    /**
     * [{"url": "http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/1.jpg"}, {"url": "http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/2.jpg"}, {"url": "http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/3.jpg"}, {"url": "http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/4.jpg"}, {"url": "http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/5.jpg"}, {"url": "http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/6.jpg"}, {"url": "http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/7.jpg"}, {"url": "http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/8.jpg"}]
     * @param headUrl
     * @param jsonString
     * @return
     */
    public static String formatJson(String headUrl,String jsonString){

        if(jsonString == null) {return "";}

        try {
            JSONObject json = JSONObject.parseObject(jsonString);

            Iterator<String> it = json.keySet().iterator();
            while(it.hasNext()){
                String key = it.next();
                if("url".equals(key) || "src".equals(key) || key.contains("card") || key.contains("videoFirstImgSrc")) {
                    if(json.get(key).toString().startsWith("http")) {
                        continue;
                    }
                    String value = json.get(key).toString().replace("\\","/");
                    json.put(key, headUrl + value);
                }
            }
            return json.toJSONString();
        }catch (Exception e){
            JSONArray jsonArray = JSONArray.parseArray(jsonString);

            for(Object o : jsonArray) {
                JSONObject json = (JSONObject)o;
                Iterator<String> it = json.keySet().iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    if("url".equals(key) || "src".equals(key) || key.contains("card") || key.contains("videoFirstImgSrc")) {
                        if(json.get(key).toString().startsWith("http")){
                            continue;
                        }
                        String value = json.get(key).toString().replace("\\","/");
                        json.put(key, headUrl + value);
                    }
                }
            }
            return jsonArray.toJSONString();
        }

    }

    /**
     * ["test/Help/image201801/youth_201801184844_5674.jpg", "test/Help/image201801/youth_201801184844_8740.jpg", "test/Help/image201801/youth_201801184844_8191.jpg"]
     * @param headUrl
     * @param stringArray
     * @return
     */
    public static String formatStringArray(String headUrl,String stringArray){
        if(stringArray == null) {return "";}
        if("[]".equals(stringArray)) {return "";}

        String[] array = stringArray.replace("[","").replace("]","").replace("\"","").split(",");

        StringBuilder result = new StringBuilder();
        result.append("\"");
        for(int i=0;i<array.length;i++){
            String str = array[i];
            str = str.replace("\\","/");
            if(i == array.length - 1 ) {
                if(str.startsWith("http")) {
                    result.append(str +"\"");
                    continue;
                }
                if("".equals(str)) {
                    result.append(str +"\"");
                    continue;
                }
                result.append(headUrl + str +"\"");
            }else{
                if(str.startsWith("http")) {
                    result.append(str + "\",\"");
                    continue;
                }
                if("".equals(str)) {
                    result.append(str + "\",\"");
                    continue;
                }
                result.append(headUrl + str + "\",\"");
            }
        }
        return "["+result.toString()+"]";
    }

    public static String formatString(String headUrl,Object str){
        if(str == null) {return "";}
        if("".equals(str)) {return "";}

        String strx = str.toString();
        if(strx.startsWith("http")) {return strx;}

        strx = strx.replace("\\","/");
        return headUrl + strx;
    }

    public static void handler(String ffmpegPath, String upFilePath, String mediaPicPath) {
        List<String> cutpic = new ArrayList<>();
        cutpic.add(ffmpegPath );
        cutpic.add("-i");
        // 同上（指定的文件即可以是转换为flv格式之前的文件，也可以是转换的flv文件）
        cutpic.add(upFilePath);
        cutpic.add("-y");
        cutpic.add("-f");
        cutpic.add("image2");
        // 添加参数＂-ss＂，该参数指定截取的起始时间
        cutpic.add("-ss");
        // 添加起始时间为第17秒
        cutpic.add("0");
        // 添加参数＂-t＂，该参数指定持续时间
        cutpic.add("-t");
        // 添加持续时间为1毫秒
        cutpic.add("0.001");
        // 添加参数＂-s＂，该参数指定截取的图片大小
        cutpic.add("-s");
        // 添加截取的图片大小为350*240
        cutpic.add("564*320");
        // 添加截取的图片的保存路径
        cutpic.add(mediaPicPath);

        ProcessBuilder builder = new ProcessBuilder();
        try {

            builder.command(cutpic);
            builder.redirectErrorStream(true);
            // 如果此属性为 true，则任何由通过此对象的 start() 方法启动的后续子进程生成的错误输出都将与标准输出合并，
            // 因此两者均可使用 Process.getInputStream() 方法读取。这使得关联错误消息和相应的输出变得更容易
            builder.start();
        } catch (Exception e) {
            logger.error(e);
        }
    }

   /** // 视频缩略图截取
    // inFile 输入文件(包括完整路径)
    // outFile 输出文件(可包括完整路径)*/
    public static boolean transfer(String ffmpegPath,String inFile, String outFile,String startTime) {
        String command = "ffmpeg -i " + inFile
                + " -y -f image2 -ss "+startTime+" -t 00:00:01 -s  564*320 "
                + outFile;
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(ffmpegPath+command);
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                logger.info(line);
            }
        } catch (Throwable t) {
            logger.error(t);
            return false;
        }
        return true;
    }


    public static void main(String[] a){
        String xx = "[{\"url\": \"http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/1.jpg\"}, {\"url\": \"http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/2.jpg\"}, {\"url\": \"http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/3.jpg\"}, {\"url\": \"http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/4.jpg\"}, {\"url\": \"http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/5.jpg\"}, {\"url\": \"http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/6.jpg\"}, {\"url\": \"http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/7.jpg\"}, {\"url\": \"http://test22umake.oss-cn-beijing.aliyuncs.com/test/Help/image201801/8.jpg\"}]";
        String xxz = formatJson("zzzzz",xx);
        System.err.println(xxz);

    }


}
